package com.xzbd.test.simple;

import org.eclipse.swt.*;

import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;

public class PictureLabel extends Canvas {

	Image image;
	String text;
	Color white;

	public PictureLabel(Composite parent, int style) {
		super(parent, style);
		white = new Color(null, 255, 255, 255);
		setBackground(white);
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				PictureLabel.this.widgetDisposed(e);
			}

		});

		addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				PictureLabel.this.paintControl(e);
			}

		});
	}

	void paintControl(PaintEvent e) {
		GC gc = e.gc;
		int x = 1;
		if (image != null) {
			gc.drawImage(image, x, 1);
			x = image.getBounds().width + 5;
		}

		if (text != null) {
			gc.drawString(text, x, 1);
		}
	}

	void widgetDisposed(DisposeEvent e) {
		white.dispose();
	}

	@Override
	public Point computeSize(int wHint, int hHint, boolean changed) {
		int width = 0, height = 0;
		if (image != null) {
			Rectangle bounds = image.getBounds();
			width = bounds.width + 5;
			height = bounds.height;
		}

		if (text != null) {
			GC gc = new GC(this);
			Point extent = gc.stringExtent(text);
			gc.dispose();
			width += extent.x;
			height = Math.max(height, extent.y);

		}

		if (wHint != SWT.DEFAULT)
			width = wHint;
		if (hHint != SWT.DEFAULT)
			height = hHint;
		return new Point(width + 2, height + 2);

	}

	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
		redraw();
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
		redraw();
	}
}
